package com.point.business.servlets;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import com.point.business.database.managers.UsersManager;

/**
 * Servlet implementation class MidnightEraserStarter
 */

public class MidnightEraserStarter extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private final static long ONCE_PER_DAY = 1000 * 60 * 60 * 24;
	private final static long EVERY_HOUR = 1000 * 60 * 60;

	private final static int ONE_DAY = 1;
	private final static int MIDNIGHT = 0;
	private final static int ZERO_MINUTES = 0;

	private Date getTomorrowMorning12pm() {
		Calendar tomorrow = Calendar.getInstance();
		tomorrow.add(Calendar.DATE, ONE_DAY);
		Calendar result = new GregorianCalendar(tomorrow.get(Calendar.YEAR),
				tomorrow.get(Calendar.MONTH), tomorrow.get(Calendar.DATE),
				MIDNIGHT, ZERO_MINUTES);
		return result.getTime();
	}

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public MidnightEraserStarter() {
		super();
	}

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		startTimerEraser();
		startTimerPinger();
	}

	/** Construct and use a TimerTask and Timer. */
	public void startTimerEraser() {
		TimerTask resetTimer = new TimerTask() {
			@Override
			public void run() {
				UsersManager.getInstance().resetUsersQueriesCounters();
			}
		};
		// perform the task once a day at 12 p.m., starting tomorrow morning
		// (other styles are possible as well)
		Timer timer = new Timer();
		timer.scheduleAtFixedRate(resetTimer, getTomorrowMorning12pm(),
				ONCE_PER_DAY);
	}

	public void startTimerPinger() {
		TimerTask pingTimer = new TimerTask() {
			@Override
			public void run() {
				UsersManager.getInstance().getAllUsers();
			}
		};
		// perform the task once a day at 12 p.m., starting tomorrow morning
		// (other styles are possible as well)
		Timer timer = new Timer();
		timer.scheduleAtFixedRate(pingTimer, 0, EVERY_HOUR);
	}

}
